<?php

namespace Controller;

class Register {
	
	public function do_control(\Model\Database $db, \View\Register $register_view) {
		
		$register_model = new \Model\Register($db);
		$validator = new \View\Validator();
		
		$message = $register_view->NO_MESSAGE;
		$success = false;
		
		// Om användaren försökt registrera sig...
		if ($register_view->tried_to_register()) {
			
			// Validera och generera eventuellt felmeddelande
			if (!$validator->not_empty($register_view->get_username())) {
				$message = $register_view->USERNAME_EMPTY;
			} elseif (!$validator->length($register_view->get_username(), 3, 20)) {
				$message = $register_view->USERNAME_LENGTH;
			} elseif (!$validator->not_empty($register_view->get_password())) {
				$message = $register_view->PASSWORD_EMPTY;
			} elseif (!$validator->length($register_view->get_password(), 6)) {
				$message = $register_view->PASSWORD_LENGTH;
			} elseif (!preg_match(\View\Validator::$REGEX_PASSWORD, $register_view->get_password())) {
				$message = $register_view->PASSWORD_FORMAT;
			} elseif ($register_view->get_password() != $register_view->get_password2()) {
				$message = $register_view->PASSWORD_REPEAT_NO_MATCH;
			} elseif (!$register_model->register_user($register_view->get_username(), $register_view->get_password())) {
				$message = $register_view->USERNAME_TAKEN;
			} else {
				$success = true;
			}
			
		}
		
		// Om registreringen lyckades...
		if ($success) {
			
			// Logga in användaren
			$login_view = new \View\Login();
			$login_view->do_login();
			
			$message = $register_view->SUCCESS . $login_view->LOGGED_IN . $login_view->get_username();
			
			return $login_view->do_logout_box($message);
			
		} else {
			return $register_view->do_output($message);
		}
		
	}
	
}

?>